// pages/myinfo/myinfo.js
import * as api from '../../utils/api.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    domain:api.domain,
    isLogin: false,
    userinfo: {},
    cooperation_article: null,
    customer_service_phone: '',
    total_order: 0,
    cityId: 0
  },
  workerLogin:function(){
    const token = wx.getStorageSync('token')
    const loginType = wx.getStorageSync('loginType')
    if (token && loginType == 'worker') {
      wx.wx.reLaunch({
        url: '/pages/worker/index',
      })
    } else {
      wx.navigateTo({
        url: '/pages/worker/login',
      })
    }
  },
  getMyInfoData(city_id = 0) {
    const that = this
    const cityId = city_id ? city_id : wx.getStorageSync('cityId');
    api.myIndex(cityId)
      .then(res => {
        that.setData({
          cooperation_article: res.data.cooperation_article,
          customer_service_phone: res.data.customer_service_phone,
          total_order: res.data.total_order,
          // userinfo: res.data.userinfo
        })
      }).catch(err => console.log(err))
  },
  callPhone() {
    const mobile = this.data.customer_service_phone
    if (mobile) {
      wx.makePhoneCall({
        phoneNumber: mobile
      })
    } else {
      const cityId = wx.getStorageSync('cityId')
      if (cityId) {
        wx.showToast({
          title: '未设置客服电话',
          icon: 'error'
        })
      } else {
        this.getFuzzyLocation('callPhone')
      }
    }
  },
  toArticle() {
    const cooperation_article = this.data.cooperation_article
    if (cooperation_article) {
      const id = cooperation_article.id
      wx.navigateTo({
        url: '/pages/articleDetail/articleDetail?id=' + id,
      })
    } else {
      const cityId = wx.getStorageSync('cityId')
      if (cityId) {
        wx.showToast({
          title: '暂未开通加盟',
          icon: 'error'
        })
      } else {
        this.getFuzzyLocation('toArticle')
      }
    }
  },
  mydata:function(){
    if (!this.data.isLogin) {
      this.loginModal()
      return false;
    }
    wx.navigateTo({
      url: '/pages/myinfo/personaldata',
    })
  },
  nextmyset:function(){
    if (!this.data.isLogin) {
      this.loginModal()
      return false;
    }
    wx.navigateTo({
      url: '/pages/myinfo/mydevice',
    })
  },
  businessLogin:function(){
    const token = wx.getStorageSync('token')
    const loginType = wx.getStorageSync('loginType')
    if (token && loginType == 'business') {
      wx.reLaunch({
        url: '/pages/business/index',
      })
    } else {
      wx.navigateTo({
        url: '/pages/business/login',
      })
    }
  },

  checkLogin() {
    const token = wx.getStorageSync('token')
    const that = this;
    if (token) {
      api.checkToken()
        .then(res => {
          let userinfo = wx.getStorageSync('userinfo')
          userinfo.avatar = userinfo.avatar.startsWith('/') ? that.data.domain + userinfo.avatar : userinfo.avatar
          that.setData({
            isLogin: true,
            userinfo
          })
        })
        .then(() => {
          that.getFuzzyLocation('checkLogin')
        })
        .catch(err => {
          console.log(err)
          that.loginModal()
        })
    } else {
      that.loginModal()
    }
  },
  loginModal() {
    const that = this
    if (!this.data.isLogin) {
      wx.showModal({
        title: '提示',
        content: '现在登录?',
        confirmText: '登录',
        cancelText: '再看看',
        success (res) {
          if (res.confirm) {
            wx.login()
              .then(res => {
                const code = res.code
                api.userLogin(code)
                  .then(res => {
                    console.log(res)
                    let userinfo = res.data.userinfo;
                    if(userinfo.avatar.startsWith('/')) {
                      wx.navigateTo({
                        url: '../personaldata/personaldata',
                      })
                    } else {
                      wx.setStorageSync('token', userinfo.token)
                      wx.setStorageSync('userinfo', userinfo)
                      wx.setStorageSync('loginType', 'user')
                      that.setData({
                        userinfo,
                        isLogin: true
                      })
                      that.getFuzzyLocation('loginModal')
                    }
                  }).catch(err => {
                    wx.showToast({
                      title: err.msg,
                      icon: 'error'
                    })
                  })
              })
              
          } else if (res.cancel) {
            wx.showToast({
              title: '您选择了取消',
              icon: 'error'
            })
          }
        }
      })
      return false
    }
  },

  logout(){
    const that = this
    if(!that.data.isLogin) {
      wx.showToast({
        title: '已经是退出状态',
        icon: 'none'
      })
      return false
    }
    api.userLogout().then(res => {
      if(res.code == 1) {
        wx.setStorageSync('token', '')
        wx.setStorageSync('userinfo', '')
        wx.setStorageSync('loginType', '')
        wx.setStorageSync('logs', '')
        that.setData({
          isLogin:false
        })
        wx.showToast({
          title: '退出成功',
          icon: 'none'
        })
        setTimeout(function(){
          that.onShow()
        },1500)
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  getFuzzyLocation(call_function = ''){
    console.log({call_function})
    const that = this
    const cityId = wx.getStorageSync('cityId')
    if (cityId) return false;
    wx.getFuzzyLocation({
      type: 'wgs84',
      success (res) {
        const latitude = res.latitude
        const longitude = res.longitude
        console.log({latitude, longitude})
        api.getAddress(latitude, longitude)
          .then(res => {
            const cityName = res.data.city_name
            const cityId = res.data.city_info.id
            wx.setStorageSync('cityName', cityName)
            wx.setStorageSync('cityId', cityId)
            that.setData({
              cityId
            })
            that.getMyInfoData(cityId)
          }).catch(err => console.log(err))
      },
      fail (err) {
        wx.showModal({
          title: '提示',
          content: '您未同意提供模糊地理位置信息，我们无法为您展示最近的客服服务信息',
          cancelText: '拒绝授权',
          confirmText: '去授权',
          complete: (res) => {
            if (res.cancel) {
              wx.showToast({
                title: '您拒绝了授权',
                icon: 'error'
              })
            }
        
            if (res.confirm) {
              wx.openSetting({
                success (res) {
                  if (res.authSetting["scope.userFuzzyLocation"]) {
                    that.getFuzzyLocation('getFuzzyLocation|openSetting')
                  } else {
                    
                  }
                }
              })
            }
          }
        })
      }
     })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.checkLogin()
    this.getMyInfoData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})